package view
{
	import laya.display.Sprite;
	import laya.display.Animation;
	import laya.events.Event;
	import laya.utils.Pool;
	import laya.maths.Point;

	/**
	 * ...
	 * @author
	 */
	public class Role extends Sprite{
		private var roleAni:Animation;
		private var bulleType:int = 1;
		public var hp:int;
		public var attack:int = 1;
		public var hitRadius:Point;

		public function Role(){
			hitRadius = new Point(99,124);
			roleAni=new Animation();
			roleAni.loadAnimation("Role.ani");

			this.addChild(roleAni)
			
			this.on(Event.ADDED,this,onAddToStage);
			this.on(Event.REMOVED,this,onRemoveFromStage);
		}

		private function onAddToStage():void
		{
			GameDispatcher.getInstance().on(EventName.GAME_PAUSE,this,onPause);
			GameDispatcher.getInstance().on(EventName.GAME_RESUME,this,onResume);
			playAction("fly");
			startAttack();
		}

		private function onRemoveFromStage():void
		{
			GameDispatcher.getInstance().off(EventName.GAME_PAUSE,this,onPause);
			GameDispatcher.getInstance().off(EventName.GAME_RESUME,this,onResume);
		}

		private function onPause():void
		{
			stopAttack();
		}

		private function onResume():void
		{
			startAttack();
		}

		/**
		 * 开始攻击
		 */
		private function startAttack():void
		{
			var time:int = GameManager.getInstance().attackTime;
			Laya.timer.loop(time,this,creatBulle);
		}

		/**
		 * 停止攻击
		 */
		private function stopAttack():void
		{
			Laya.timer.clear(this,creatBulle);
		}

		/**
		 * 创建子弹
		 */
		private function creatBulle():void
		{
			var bulle:Bulle = Pool.getItemByClass("bulle", Bulle);
			bulle.init(this.x,this.y,bulleType,attack);
		}

		private function playAction(name:String,isLoop:Boolean = true):void
		{
			roleAni.play(0,isLoop,"hero_" + name);
		}

		/**
		 * 受击
		 */
		public function hit(num:int):void
		{
			hp -= num;
			if(hp <= 0)
			{
				hp = 0;
				die();
			}
			GameDispatcher.getInstance().event(EventName.HP_CHANGE);
		}

		public function die():void
		{
			playAction("die",false);
			stopAttack();
			GameDispatcher.getInstance().event(EventName.GAME_OVER);
			Laya.timer.frameOnce(8,this,clear);
		}

		private function clear():void
		{
			this.removeSelf();
		}
	}

}